package com.mall.mymall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.mymall.dao.dto.UserDto;
import com.mall.mymall.dao.entity.Users;
import com.mall.mymall.mapper.UsersMapper;
import com.mall.mymall.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 十里坡
 * @since 2025-03-06
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    // 实现根据用户ID查询用户的方法
    @Override
    public Users getUserById(Integer userId) {
        return this.getById(userId);
    }

    // 实现查询所有用户的方法
    @Override
    public List<Users> getAllUsers() {
        return this.list(); // 使用MyBatis-Plus的list()方法查询所有用户
    }

    @Override
    public Users getUserByUsername(String username) {
        // 使用MyBatis-Plus的QueryWrapper构造查询条件
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username); // 等价于 SQL: WHERE username = ?
        return this.getOne(queryWrapper); // 查询单个用户
    }

    @Override
    public Users register(UserDto userDto) {
        synchronized (userDto.getUsername().intern()) {
            //先查用户名
            Users user = this.getUserByUsername(userDto.getUsername());
            if (user != null) {
                throw new RuntimeException("用户名已经注册了");
            }
            user = new Users(null,
                    userDto.getUsername(),
                    userDto.getPassword(),
                    userDto.getEmail(),
                    userDto.getPhone(),
                    userDto.getRoleId(),
                    LocalDateTime.now());
            this.baseMapper.insert(user);
            return user;
        }
    }
}